package nsq

import (
	"fmt"
	"github.com/nsqio/go-nsq"
	"server/pkg/log"
)

type NsqClient struct {
	Host     string
	Port     int64
	Producer *nsq.Producer
}

func (n *NsqClient) GetProducer() *nsq.Producer {
	if n.Producer.Ping() != nil {
		n.Producer, _ = NewClient(n.Host, n.Port)
	}
	return n.Producer
}

func (n *NsqClient) PushMessageToNsq(msg NsqMessage) error {
	producer := n.GetProducer()

	// 发布消息
	err := producer.Publish(string(msg.Topic), msg.Message)
	if err != nil {
		log.Error("nsq", err, "nsq生产者发布消息失败")
		return err
	}
	return nil
}

func NewNsqClient(host string, port int64) *NsqClient {
	producer, _ := NewClient(host, port)
	return &NsqClient{
		Host:     host,
		Port:     port,
		Producer: producer,
	}
}

func NewClient(host string, port int64) (*nsq.Producer, error) {
	addr := fmt.Sprintf("%s:%d", host, port)
	producer, err := nsq.NewProducer(addr, nsq.NewConfig())
	if err != nil {
		log.Error("nsq", err, "nsq生产者初始化对象尝试创建初始化失败")
		return nil, err
	}

	// PING测试
	err = producer.Ping()
	if err != nil {
		log.Error("nsq", err, "nsq生产者连接失败")
		return nil, err
	}

	return producer, nil
}
